package com.now.printer.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.now.printer.base.BaseActivity2;
import com.now.printer.R;
import com.now.printer.utils.ConvertUtils;
import com.now.printer.utils.FileUtils;
import com.now.printer.utils.PrinterUtils;
import com.now.printer.utils.Utils;
import com.xuexiang.xutil.tip.ToastUtils;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.AppCompatSeekBar;

import org.xutils.common.util.LogUtil;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.jarlen.photoedit.utils.LittleUtil;

/**
 * Created by xudong on 2021/6/10.
 */

public class StickyNoteActivity extends BaseActivity2 implements View.OnClickListener {

    private LinearLayout main;
    private ImageView imgBack;
    private ImageView imgPrint;
    private TextView txtSave;
    private ScrollView svContent;
    private LinearLayout layoutContent;
    private EditText etContent;
    private LinearLayout llBottomPro;
    private AppCompatSeekBar txtSeekBar;
    private ImageView imgHind;
    private LinearLayout llAction;
    private ImageView ivStickNoteSpace;
    private ImageView ivStickNoteEnter;
    private RelativeLayout rlStickNoteLength;
    private ImageView ivStickNoteDelete;
    private ImageView ivStickNoteKeyboard;
    private ImageView ivStickNoteHandWrite;
    private ImageView imageBg;

    String path = "";

    @Override
    public int getLayoutId() {
        return R.layout.activity_sticky_note;
    }

    @Override
    public void doBusiness(Context mContext) {
        path = Environment.getExternalStorageDirectory().getPath() + File.separator + getString(R.string.app_name);
        main = (LinearLayout) findViewById(R.id.main);
        imgBack = (ImageView) findViewById(R.id.img_back);
        imgPrint = (ImageView) findViewById(R.id.imgPrint);
        imgPrint.setOnClickListener(this);

        txtSave = (TextView) findViewById(R.id.txtSave);
        txtSave.setOnClickListener(this);
        svContent = (ScrollView) findViewById(R.id.sv_content);
        layoutContent = (LinearLayout) findViewById(R.id.layout_content);
        imageBg = (ImageView) findViewById(R.id.image_bg);
        etContent = (EditText) findViewById(R.id.et_content);
        llBottomPro = (LinearLayout) findViewById(R.id.ll_bottom_pro);
        txtSeekBar = (AppCompatSeekBar) findViewById(R.id.txt_seekBar);
        imgHind = (ImageView) findViewById(R.id.imgHind);
        llAction = (LinearLayout) findViewById(R.id.ll_action);
        ivStickNoteSpace = (ImageView) findViewById(R.id.iv_stick_note_space);
        ivStickNoteEnter = (ImageView) findViewById(R.id.iv_stick_note_enter);
        rlStickNoteLength = (RelativeLayout) findViewById(R.id.rl_stick_note_length);
        ivStickNoteDelete = (ImageView) findViewById(R.id.iv_stick_note_delete);
        ivStickNoteKeyboard = (ImageView) findViewById(R.id.iv_stick_note_keyboard);
        ivStickNoteHandWrite = (ImageView) findViewById(R.id.iv_stick_note_hand_write);


//        Utils.showSoftKeyboard(this, etContent);

        imgBack.setOnClickListener(this);
        ivStickNoteSpace.setOnClickListener(this);
        ivStickNoteEnter.setOnClickListener(this);
        ivStickNoteDelete.setOnClickListener(this);
        ivStickNoteKeyboard.setOnClickListener(this);
        imgHind.setOnClickListener(this);
        rlStickNoteLength.setOnClickListener(this);
        initView();
    }

    private void initView() {
        imageBg.setAdjustViewBounds(true);
        etContent.setMaxHeight(LittleUtil.getScreenHeight(this) - LittleUtil.dip2px(this, 200f));
        imageBg.setMaxHeight(LittleUtil.getScreenHeight(this) - LittleUtil.dip2px(this, 200f));
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) etContent.getLayoutParams();
        layoutParams.bottomMargin = LittleUtil.dip2px(this, 20f);
        layoutParams.topMargin = LittleUtil.dip2px(this, 90f);
        layoutParams.leftMargin = LittleUtil.dip2px(this, 50f);
        layoutParams.rightMargin = LittleUtil.dip2px(this, 50f);
        etContent.setLayoutParams(layoutParams);

        txtSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // 当拖动条的滑块位置发生改变时触发该方法,在这里直接使用参数progress，即当前滑块代表的进度值
                int length = etContent.getText().toString().length();
                double bili = Math.floorDiv(progress * length, 100);
                int selection = (int) (bili * length);
                etContent.setSelection((int) bili);

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                Log.e("------------", "开始滑动！");
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                Log.e("------------", "停止滑动！");
            }
        });
    }


    /**
     * 保存截图到本地
     *
     * @param bitmap 截取到的图片
     */

    private String currentFileName = "";
    private boolean saveScreenShotToSD(Bitmap bitmap) {

        if (bitmap != null) {
            if (FileUtils.isSDCardAvailable()) {  //如果SD存储设备可用
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdir();   //创建目录
                }
                currentFileName = System.currentTimeMillis() + ".png";
                File file = new File(dir,currentFileName);
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(file);

                    //根据指定的格式、质量、输出流 将bitmap保存到本地，并返回是否保存成功
                    boolean saveSuccess = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);

                    if (saveSuccess) {
                        updateGallery(file);    //刷新相册
                    }

                    return saveSuccess;
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                    return false;
                } finally {
                    if (fos != null) {
                        try {
                            fos.close();    //关闭流防止溢出
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            } else {
                ToastUtils.toast("本地存储空间不可用");
            }
        }
        return false;
    }
    /**
     * 发送广播更新相册，不更新的话，在相册中将无法查看到截取的图片
     */
    private void updateGallery(File file) {
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        sendBroadcast(intent);
    }
    private Bitmap getLayoutBitmap(){
        layoutContent.setDrawingCacheEnabled(true);
        //测量大小
        layoutContent.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        //发送尺寸到view和子view
        layoutContent.layout(0, 0, layoutContent.getMeasuredWidth(),layoutContent.getMeasuredHeight());
        //获取可视组件的截图
        Bitmap cacheBitmap = layoutContent.getDrawingCache();
        return cacheBitmap;
    }


    @Override
    public void onClick(View v) {
        int index = etContent.getSelectionStart();//获取光标所在位置
        Editable edit = etContent.getEditableText();//获取EditText的文字
        switch (v.getId()) {
            case R.id.imgPrint:
                boolean isSaveAndPrint = saveScreenShotToSD(getLayoutBitmap());

                x.task().run(new Runnable() {
                    @Override
                    public void run() {

                        ToastUtils.toast(isSaveAndPrint?"保存成功":"保存失败");
                        String inputPath = path + File.separator + currentFileName;
                        String outputPath = inputPath +  ".pdf";

                        LogUtil.i("我的输出文件是 : " + outputPath);
                        ConvertUtils.convertImageToPdf(StickyNoteActivity.this,inputPath,outputPath);

                        PrinterUtils.doPrint(StickyNoteActivity.this,outputPath);
                    }
                });


                break;
            case R.id.txtSave:
                boolean isSave = saveScreenShotToSD(getLayoutBitmap());
                ToastUtils.toast(isSave?"保存成功":"保存失败");
                break;
            case R.id.iv_stick_note_space:
                String text = " ";
                if (index < 0 || index >= edit.length()) {
                    edit.append(text);
                } else {
                    edit.insert(index, text);//光标所在位置插入文字
                }
                break;
            case R.id.iv_stick_note_enter:
                String text2 = "\n";
                if (index < 0 || index >= edit.length()) {
                    edit.append(text2);
                } else {
                    edit.insert(index, text2);//光标所在位置插入文字
                }
                break;
            case R.id.iv_stick_note_delete:
                if (etContent.length() != 0 && index > 0) {
                    edit.delete(index - 1, index);
                }
                break;
            case R.id.iv_stick_note_keyboard:

                Rect rect = new Rect();
                this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);//获取当前界面可视部分
                int screenHeight = this.getWindow().getDecorView().getRootView().getHeight();//获取屏幕高度
                int heiDifference = screenHeight - rect.bottom;//获取键盘高度，键盘没有弹出时，高度为0，键盘弹出时，高度为正数
                if (heiDifference == 0) {
                    // 键盘打开状态
                    Utils.hideSoftKeyboard(this, etContent);
                } else {
                    Utils.showSoftKeyboard(this, etContent);
                }
//                if (Utils.isShowSoftKeyboard(this, etContent)) {
//                    Utils.hideSoftKeyboard(this, etContent);
//                } else {
//                    Utils.showSoftKeyboard(this, etContent);
//                }
                break;
            case R.id.rl_stick_note_length:
                if (llBottomPro.getVisibility() == View.VISIBLE) {
                    llBottomPro.setVisibility(View.GONE);
                } else {
                    llBottomPro.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.imgHind:
                llBottomPro.setVisibility(View.GONE);
                break;
            case R.id.img_back:
                onBackPressed();
                break;
        }
    }


}
